﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Media;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;
using MyLog;

namespace Notification {
    public partial class FrmMain : Form {
        private bool _hasNewMessage;
        private readonly Icon[] _icons;

        public FrmMain() {
            InitializeComponent();

            _icons = new[]
            {
                Icon.FromHandle(Resource.bell_r.ToBitmap().GetHicon()),
                Icon.FromHandle(Resource.bell_g.ToBitmap().GetHicon())
            };
        }

        private void FrmMain_Load(object sender, EventArgs e) {
            Text = String.Format("用户【{0}】的消息列表", Program.CurrentUserName);
            webBrowser.Navigate(new Uri(ConfigurationManager.AppSettings["url"] + Program.CurrentUserId));

            // 设置定时器间隔时间（最少5秒）
            var interval = Int32.Parse(ConfigurationManager.AppSettings["interval"]);
            if (interval < 5000) {
                interval = 5000;
            }
            timer.Interval = interval;
            // 启动定时器
            timer.Start();

            Icon = _icons[0];
            notifyIcon.Icon = _icons[0];
            Visible = false;
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {
            if (e.CloseReason == CloseReason.UserClosing) {
                Visible = false;
                e.Cancel = true;
                return;
            }

            timer.Stop();
            e.Cancel = false;
            Application.Exit();
            Dispose();
        }

        /// <summary>
        ///     定时检测是否有新消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e) {
            var sql = "SELECT * FROM T_Message WHERE ReceiverId=" + Program.CurrentUserId +
                      " AND IsRead=0 ORDER BY SendTime DESC";
            var dataSet = new DataSet();
            SqlHelper.FillDataset(SqlHelper.GetConnString(), CommandType.Text, sql, dataSet, new[] { "tmp" });
            var dataTable = dataSet.Tables["tmp"];
            if (dataTable.Rows.Count > 0) {
                webBrowser.Navigate(new Uri(ConfigurationManager.AppSettings["url"] + Program.CurrentUserId));

                // 有新的未读消息，提示用户
                timerNewMessage.Start();
                if (!Visible) {
                    notifyIcon.ShowBalloonTip(500, @"有新的消息", @"您有一条新的短消息，请查收。", ToolTipIcon.Info);
                }
            }
        }

        /// <summary>
        ///     显示闪烁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerNewMessage_Tick(object sender, EventArgs e) {
            // 如果主窗体显示，则不在闪烁
            if (Visible) {
                // 恢复默认图标
                notifyIcon.Icon = _icons[0];
                _hasNewMessage = false;

                timerNewMessage.Stop();
                return;
            }
            // 切换图片，闪烁并播放声音，提醒用户关注
            notifyIcon.Icon = _icons[DateTime.Now.Millisecond % 2];
            if (!_hasNewMessage) {
                var player = new SoundPlayer(Resource.tip);
                player.PlaySync();
                _hasNewMessage = !_hasNewMessage;
            }
        }

        private void notifyIcon_BalloonTipClicked(object sender, EventArgs e) {
            // 恢复默认图标
            notifyIcon.Icon = _icons[0];
            _hasNewMessage = false;
            Visible = true;
            WindowState = FormWindowState.Normal;

            timerNewMessage.Stop();
        }

        private void notifyIcon_BalloonTipClosed(object sender, EventArgs e) {
            _hasNewMessage = true;
        }

        private void notifyIcon_BalloonTipShown(object sender, EventArgs e) {
            _hasNewMessage = false;
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) {
            notifyIcon_BalloonTipClicked(sender, e);
        }

    }
}